package com.zk.shop.servlet.order;

import com.zk.shop.entity.Goods;
import com.zk.shop.entity.Order;
import com.zk.shop.entity.User;
import com.zk.shop.service.GoodsService;
import com.zk.shop.service.Impl.GoodsServicesImpl;
import com.zk.shop.service.Impl.OrderServiceImpl;
import com.zk.shop.service.OrderService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static com.zk.shop.util.OrderCodeFactory.getRefundCode;

@WebServlet("addOrderServlet")
public class addOrderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String[] totalPrice=req.getParameterValues("totalPrices");
        String[] buyNum= req.getParameterValues("buyNums");
        String[] goodsId= req.getParameterValues("goodsIds");
        HttpSession session=req.getSession();
        User buyer= (User) session.getAttribute("user");
        int[] goodsIds=new int[goodsId.length];
        int[] buyNums=new int[buyNum.length];
        double[] totalPrices=new double[totalPrice.length];
        int[] sellerIds=new int[goodsId.length];
        OrderService orderService=new OrderServiceImpl();
        GoodsService goodsService=new GoodsServicesImpl();

        List<Order> orderList=new ArrayList<>();
        Order order;
        for (int i = 0; i < goodsId.length; i++) {
            order=new Order();
            String orderNum = getRefundCode(Long.parseLong("1"));
            goodsIds[i]=Integer.parseInt(goodsId[i]);
            buyNums[i]=Integer.parseInt(buyNum[i]);
            Goods goods=goodsService.getThisGoodsById(goodsIds[i]);
            double price=goods.getPrice();
            BigDecimal p1 = new BigDecimal(Double.toString(price));
            BigDecimal p2 = new BigDecimal(Double.toString(buyNums[i]));
            totalPrices[i]=p1.multiply(p2).doubleValue();
            sellerIds[i]=goods.getUser().getUserId();
            User seller=new User();

            seller.setUserId(sellerIds[i]);
            goods.setGoodsId(goodsIds[i]);
            order.setOrderNum(orderNum);
            order.setBuyer(buyer);
            order.setSeller(seller);
            order.setGoods(goods);
            order.setState(0);
            order.setTotalPrice(totalPrices[i]);
            order.setSellNum(buyNums[i]);
            orderList.add(order);
        }

        boolean flag=orderService.addOrder(orderList);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
